Introduction to Python Day 2

Verjinia Metodieva and Daniel Parthier

2025-02-04

Jupyter Notebook

Recap homework

Let’s take a look at the homework

Functions part 2

Goal of today

# TODO: add useful example to introduce class
# Some function we have to decide
def useful_function(par1, par2, par3):
    # some loop
    for i in par1:
        if par1 == "something":
            # do something
        else:
            pass # or something else
    return None # or an object 

Global vs. Local

  • Scopes
  • Local variables live and die inside a function
  • Global variables
    • declared outside of fucntions
    • lost when programme closed

Short interlude

  • Whole numbers: Integers int
type(1)
int
  • Real numbers: Floats float
type(1.0)
float
  • Most of the time it might not matter1
1 == 1.0
True
  • Sometimes there is a difference and we will see later why

Conditional statements

The important question of what to do “if” something happens.

  • Programming languages are languages
  • if something is True
    • you should do something
  • else
    • do something else
if statement:
    print("the statement is true")
else:
    print("the statement is false")

Multiple if-statements

value = 3
1if value == 1:
    print("the value is 2")
2elif value == 2:
    print("the value is 2")
3elif value == 3:
4    print("the value is 3")
else:
    print("the value is something else")
1
Check if value is 1
2
Check if value is 2
3
Check if value is 3
4
Execute block
the value is 3

How to check if everything is true?

For loops

for *element* in *iterable*:
    *body*
  • iteration is the repetition of a process until a specific condition is met
  • what’s iterable?
# calcualte a sum
list_to_sum = [2,3,4,5,7]
num_sum = 0
for val in list_to_sum:
   num_sum = num_sum + val

TO DO

Given:
A = [3, 4, 5, 9, 12, 87, -65, 300, 450, -32]

Use for loops to:
1. Add 3 to each element of the list
2. Calculate the average of the list, but negative values are calcualted as 0s
3. Find the maximum valuen
4. Find the index (position) of the max value

Index based for loops - range()

  • generates integer sequences
  • range(n) generates the series of n values from 0 to n − 1
for i in range(5):
    print(i)
0
1
2
3
4
# looping through data indices. find the max
B = [1, 4, 6, 7, 89, 54]
big_indx = 0
for i in range(len(B)):
    if B[i] > B[big_indx]:
        big_indx = i
print('The max value in B is', B[big_indx], 'found on position', big_indx)
The max value in B is 89 found on position 4

Index based for loops - enumerate()

  • assigns a count to each item within an iterable and returns it as an enumerate object
import numpy as np

array_a = np.arange(20, 25)
for indx, val in enumerate(array_a):
    print('the index is', indx)
    print('the value is', val)
the index is 0
the value is 20
the index is 1
the value is 21
the index is 2
the value is 22
the index is 3
the value is 23
the index is 4
the value is 24

! range() and enumerate() - none of the two returs a list of objects!

Index based for loops [1]

enumerate()

  • one way to avoid nested loops

Break and continue statements

  • break - oimmediately terminates the loop

List comprehension

Compare different functions

While loops

  • Perform a task while something is True
  • Be careful:
    • Some loops never finish (get stuck)
    • Make sure that condition for ending the loop can be fullfilled
while check_condition:
    perform_task()

Errors and how to read them

There are useful resources regarding errors

  • Simply googling works surprisingly well
  • You will often end up on stackoverflow
    • There is no question which was not already asked1

Types of errors

  1. SyntaxErrors
  2. NameError
  3. TypeError
  4. IndexError
  5. AttributeError
  6. etc.

Fix errors